<template>
  <el-row>
    <el-card>
      <el-row class="title">
        <el-col :span="12">
          {{ $t('coupon.title') }}
          <span>
            {{ $t('coupon.Remarks') }}、{{ $t('coupon.list.interestrateReduction') }}、{{ $t('coupon.list.dayFree') }}
          </span>
        </el-col>
        <el-col :span="12">
          <el-button @click="addItem">{{ $t('coupon.add') }}</el-button>
          <el-button @click="view">{{ $t('coupon.view') }}</el-button>
        </el-col>
      </el-row>
      <el-divider />
      <el-form ref="searchForm" :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item :label="$t('coupon.list.prompt.allActivities')">
          <el-select v-model="searchForm.couponStatus" clearable :placeholder="$t('common.select')">
            <el-option
              v-for="item in $t('coupon.list.activityStatus')"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('coupon.list.prompt.offerType')">
          <el-select v-model="searchForm.couponType" clearable :placeholder="$t('common.select')">
            <el-option
              v-for="item in $t('coupon.list.offer')"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('coupon.list.prompt.receiveType')">
          <el-select v-model="searchForm.obtainType" clearable :placeholder="$t('common.select')">
            <el-option
              v-for="item in $t('coupon.list.receiveData')"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('coupon.list.couponId')">
          <el-input v-model="searchForm.id" :placeholder="$t('common.input')" :maxlength="50" />
        </el-form-item>
        <el-form-item :label="$t('coupon.list.couponName')">
          <el-input v-model="searchForm.couponName" :placeholder="$t('common.input')" :maxlength="50" />
        </el-form-item>
        <el-row>
          <el-button type="primary" @click="search">
            {{ $t('common.search') }}
          </el-button>
          <el-button @click="reset">
            {{ $t('common.reset') }}
          </el-button>
        </el-row>
      </el-form>
    </el-card>
    <el-card>
      <el-table
        v-loading="loading"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        :data="tableData"
        border
        :stripe="true"
        style="width: 100%"
      >
        <el-table-column
          fixed="left"
          prop="id"
          :label="tableText['couponId']"
          min-width="100"
        />
        <el-table-column
          fixed="left"
          prop="couponName"
          :label="tableText['couponName']"
          min-width="170"
        />
        <el-table-column
          prop="createTimeToString"
          :label="tableText['createTime']"
          min-width="170"
        />
        <el-table-column
          prop="obtainType"
          :label="tableText['receiveType']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ setValue(scope.row['obtainType'], 'receive') }}
          </template>
        </el-table-column>
        <el-table-column
          prop="couponType"
          :label="tableText['offerType']"
          min-width="100"
        >
          <template slot-scope="scope">
            {{ setValue(scope.row['couponType'], 'offer') }}
          </template>
        </el-table-column>
        <el-table-column
          prop="couponCondition"
          :label="tableText['preferentialConditions']"
          min-width="300"
        >
          <template slot-scope="scope">
            {{ condition(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="couponCirculation"
          :label="tableText['circulation']"
          min-width="100"
        />
        <el-table-column
          prop="receiveCount"
          :label="tableText['received']"
          min-width="100"
        />
        <el-table-column
          prop="usedCount"
          :label="tableText['used']"
          min-width="100"
        />
        <el-table-column
          prop="expDays"
          :label="tableText['effectiveTime']"
          min-width="220"
        >
          <template slot-scope="scope">
            {{ scope.row['beginDate'] && scope.row['endDate'] ? scope.row['beginDate'] + ' ---- ' + scope.row['endDate'] : '' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="pauseButton"
          :label="tableText['emergencySuspension']"
          min-width="120"
        >
          <template slot-scope="scope">
            <el-switch
              :value="scope.row['pauseButton'] === 1"
              @change="pauseButton(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="couponStatus"
          :label="tableText['Status']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ setValue(scope.row.couponStatus, 'status') }}
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('common.operate.name')"
          min-width="300"
        >
          <template slot-scope="scope">
            <el-button size="small" @click="editItem(scope.row)">
              {{ $t('coupon.list.btnGroup.couponSetting') }}
            </el-button>
            <el-button size="small" @click="deleteItem(scope.row)">
              {{ $t('common.operate.delete') }}
            </el-button>
            <el-button size="small" @click="pushItem(scope.row)">
              {{ $t('coupon.list.btnGroup.appPush') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :current-page="searchForm.currentPage"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="searchForm.pageSize"
          :total="totalNumber"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <delete-dialog
      ref="delete-dialog"
      :delete-state="deleteState"
      :loading="deleteLoading"
      @change-delete="changeDelete"
      @delete-this="deleteThis"
    />
    <use-rule-dialog
      :show-dialog="viewDialog"
      @change-dialog="changeDialog"
    />
    <app-push-dialog
      :show-dialog="pushDialog"
      :loading="pushLoading"
      @change-dialog="changeDialog"
      @app-push="appPush"
    />
    <coupon-dialog
      ref="coupon-dialog"
      :show-dialog="editDialog"
      :choose-item="chooseItem"
      @change-dialog="changeDialog"
      @edit-success="editSuccess"
    />
  </el-row>
</template>

<script>
import { getCouponList, updatePauseButton, deleteCoupon, pushMessage } from '@/api/operation'
import UseRuleDialog from '@/components/operation/use-rule-dialog'
import appPushDialog from '@/components/operation/app-push-dialog'
import CouponDialog from '@/components/operation/coupon-dialog'
import deleteDialog from '@/components/delete/index.vue'
export default {
  name: 'Coupon',
  components: {
    UseRuleDialog,
    deleteDialog,
    appPushDialog,
    CouponDialog
  },
  data() {
    return {
      loading: false,
      editDialog: false,
      deleteState: false,
      deleteLoading: false,
      pushDialog: false,
      pushLoading: false,
      tableData: [],
      tableText: {},
      totalNumber: 0,
      promotionData: [],
      searchForm: this.params(),
      viewDialog: false,
      id: null,
      chooseItem: {
        id: null,
        couponName: null,
        couponDescription: null,
        effectiveDays: null,
        createTime: null,
        obtainType: null,
        expDays: null,
        couponDays: null,
        couponPeoples: null,
        couponType: null,
        couponCondition: null,
        couponValue: null,
        couponCirculation: 1,
        dateType: null,
        effectiveDate: null,
        expDate: null,
        couponLimit: 1
      }
    }
  },
  mounted() {
    this.tableText = this.$t('coupon.list.table')
    this.getData()
  },
  methods: {
    params() {
      return {
        currentPage: 1,
        pageSize: 10,
        id: null,
        couponName: null,
        couponStatus: '',
        couponType: '',
        obtainType: ''
      }
    },
    setValue(value, data) {
      const map = this.$t(`coupon.list.${data}`)
      const name = map.filter(item => {
        return item.value.toString() === value.toString()
      })
      return (name.length > 0 && name[0].desc) ? name[0].desc : ''
    },
    search() {
      this.searchForm.currentPage = 1
      this.getData()
    },
    reset() {
      this.searchForm = this.params()
      this.getData()
    },
    getData() {
      this.loading = true
      const data = this.searchForm
      getCouponList(data)
        .then(res => {
          this.loading = false
          if (res.success) {
            this.tableData = res.data
            this.totalNumber = res.page ? res.page['totalNumber'] : 0
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error(err.message)
        })
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.searchForm.currentPage = val
      this.getData()
    },
    condition(item) {
      let str
      const status = item['couponCondition']
      const type = item['couponType']
      const unit = this.$t('common.unit')
      const loan = this.$t('coupon.list.setting.loan')
      const nothreshold = this.$t('coupon.list.setting.nothreshold')
      if (status) {
        switch (type) {
          case 1: {
            str = loan + status + unit + ', ' + this.$t('coupon.list.setting.interestReduction') + item['couponValue'] + unit
            break
          }
          case 2: {
            str = loan + status + unit + ', ' + this.$t('coupon.list.offertips.interestReduction') + item['couponValue'].toFixed(2) + '%'
            break
          }
          case 3: {
            str = loan + status + unit + ', ' + item['couponDays'] + this.$t('coupon.list.offertips.dayFree')
            break
          }
        }
      } else {
        switch (type) {
          case 1: {
            str = nothreshold + ', ' + this.$t('coupon.list.setting.interestReduction') + item['couponValue'] + unit
            break
          }
          case 2: {
            str = nothreshold + ', ' + this.$t('coupon.list.offertips.interestReduction') + item['couponValue'].toFixed(2) + '%'
            break
          }
          case 3: {
            str = nothreshold + ', ' + item['couponDays'] + this.$t('coupon.list.offertips.dayFree')
            break
          }
        }
      }
      return str
    },
    pauseButton(item) {
      const data = {
        id: item.id,
        pauseButton: item.pauseButton === 0 ? 1 : 0,
        effectiveDate: item.effectiveDate,
        expDate: item.expDate
      }
      this.loading = true
      updatePauseButton(data)
        .then(res => {
          this.loading = false
          if (res.success) {
            this.$message.success(this.$t('common.tip.editSuccess'))
            this.getData()
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error(err.message)
        })
    },
    changeDialog(data, state) {
      this[data] = state
    },
    view() {
      this.viewDialog = true
    },
    deleteItem(data) {
      this.id = data.id
      this.deleteState = true
    },
    changeDelete(param) {
      this.deleteState = param
    },
    editSuccess() {
      this.choose({})
      this.getData()
    },
    deleteThis() {
      this.deleteLoading = true
      const id = this.id
      deleteCoupon(id)
        .then(res => {
          this.deleteLoading = false
          if (res.success) {
            this.$message.success(this.$t('common.tip.deleteSuccess'))
            this.deleteState = false
            this.getData()
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.deleteLoading = false
          this.$message.error(err.message)
        })
    },
    pushItem(item) {
      this.id = item.id
      this.pushDialog = true
    },
    appPush() {
      this.pushLoading = true
      const id = this.id
      pushMessage(id)
        .then(res => {
          this.pushLoading = false
          if (res.success) {
            this.$message.success(this.$t('common.tips.operateSuccess'))
            this.pushDialog = false
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.pushLoading = false
          this.$message.error(err.message)
        })
    },
    editItem(item) {
      this.choose(item)
      this.editDialog = true
    },
    addItem() {
      this.choose({})
      this.editDialog = true
    },
    choose(param) {
      this.chooseItem.id = param.id
      this.chooseItem.couponName = param.couponName
      this.chooseItem.couponDescription = param.couponDescription
      this.chooseItem.effectiveDays = param.effectiveDays
      this.chooseItem.createTime = param.createTime
      this.chooseItem.obtainType = param.obtainType
      this.chooseItem.expDays = param.expDays
      this.chooseItem.couponDays = param.couponDays
      this.chooseItem.couponPeoples = param.couponPeoples
      this.chooseItem.couponType = param.couponType
      this.chooseItem.couponCondition = param.couponCondition
      this.chooseItem.couponValue = param.couponValue
      this.chooseItem.couponCirculation = param.couponCirculation
      this.chooseItem.dateType = param.dateType
      this.chooseItem.effectiveDate = param.effectiveDate
      this.chooseItem.expDate = param.expDate
      this.chooseItem.couponLimit = param.couponLimit
      if (param.expDays) {
        this.$refs['coupon-dialog'].changeChecked(true)
      }
      if (param.effectiveDate && param.expDate) {
        this.$refs['coupon-dialog'].setTimeValue(param.effectiveDate, param.expDate)
      }
      const value = param.couponType === 3 ? param.couponDays : param.couponValue
      if (param.couponCondition) {
        this.$refs['coupon-dialog'].changeRadio(1)
        this.$refs['coupon-dialog'].changeRadioValue('radioValue1', value)
      } else {
        if (param.couponDays || param.couponValue) {
          this.$refs['coupon-dialog'].changeRadio(2)
          this.$refs['coupon-dialog'].changeRadioValue('radioValue2', value)
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card{
  margin: 10px;
}
.title{
  font-size: 22px;
  line-height: 35px;
  span{
    font-size:12px;
    color:#999999;
    margin-left: 10px;
  }
  .el-col:last-child{
    text-align: right;
  }
}
.el-divider{
  margin: 5px 0 15px 0;
}
</style>
